using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// 章节内容修复结果
    /// </summary>
    public class ChapterRepairResult
    {
        public bool IsSuccess { get; set; }
        public string Message { get; set; } = string.Empty;
        public List<string> RepairedChapters { get; set; } = new List<string>();
        public List<string> FailedChapters { get; set; } = new List<string>();
        public int TotalProcessed { get; set; }
    }

    /// <summary>
    /// 章节内容修复服务
    /// 用于检查和修复不完整或格式错误的章节内容
    /// </summary>
    public class ChapterContentRepairService
    {
        private readonly ILogger<ChapterContentRepairService> _logger;
        private readonly ContentQualityService _contentQualityService;
        private readonly StepByStepWritingService _stepByStepWritingService;
        private readonly IAIService _aiService;

        public ChapterContentRepairService(
            ILogger<ChapterContentRepairService> logger,
            ContentQualityService contentQualityService,
            StepByStepWritingService stepByStepWritingService,
            IAIService aiService)
        {
            _logger = logger;
            _contentQualityService = contentQualityService;
            _stepByStepWritingService = stepByStepWritingService;
            _aiService = aiService;
        }

        /// <summary>
        /// 检查项目中的所有章节内容质量
        /// </summary>
        public async Task<List<string>> CheckProjectChapterQualityAsync(string projectPath)
        {
            var problematicChapters = new List<string>();

            if (!Directory.Exists(projectPath))
            {
                _logger.LogWarning($"项目路径不存在: {projectPath}");
                return problematicChapters;
            }

            var chapterPath = Path.Combine(projectPath, "章节");
            if (!Directory.Exists(chapterPath))
            {
                _logger.LogWarning($"章节目录不存在: {chapterPath}");
                return problematicChapters;
            }

            var chapterFiles = Directory.GetFiles(chapterPath, "*.txt", SearchOption.TopDirectoryOnly);
            _logger.LogInformation($"找到 {chapterFiles.Length} 个章节文件");

            foreach (var filePath in chapterFiles)
            {
                try
                {
                    var content = await File.ReadAllTextAsync(filePath);
                    var qualityResult = _contentQualityService.CheckChapterContent(content, 6500);

                    if (!qualityResult.IsValid || HasCriticalIssues(content))
                    {
                        problematicChapters.Add(filePath);
                        _logger.LogWarning($"发现问题章节: {Path.GetFileName(filePath)} - {string.Join(", ", qualityResult.Issues)}");
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, $"检查章节文件失败: {filePath}");
                    problematicChapters.Add(filePath);
                }
            }

            return problematicChapters;
        }

        /// <summary>
        /// 修复项目中的所有问题章节
        /// </summary>
        public async Task<ChapterRepairResult> RepairProjectChaptersAsync(
            string projectPath, 
            CancellationToken cancellationToken = default)
        {
            var result = new ChapterRepairResult();

            try
            {
                _logger.LogInformation($"开始修复项目章节: {projectPath}");

                // 检查问题章节
                var problematicChapters = await CheckProjectChapterQualityAsync(projectPath);
                result.TotalProcessed = problematicChapters.Count;

                if (problematicChapters.Count == 0)
                {
                    result.IsSuccess = true;
                    result.Message = "所有章节内容质量良好，无需修复";
                    return result;
                }

                _logger.LogInformation($"发现 {problematicChapters.Count} 个需要修复的章节");

                // 逐个修复章节
                foreach (var chapterFile in problematicChapters)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    try
                    {
                        var repaired = await RepairSingleChapterAsync(chapterFile, projectPath, cancellationToken);
                        if (repaired)
                        {
                            result.RepairedChapters.Add(Path.GetFileName(chapterFile));
                            _logger.LogInformation($"成功修复章节: {Path.GetFileName(chapterFile)}");
                        }
                        else
                        {
                            result.FailedChapters.Add(Path.GetFileName(chapterFile));
                            _logger.LogWarning($"修复章节失败: {Path.GetFileName(chapterFile)}");
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, $"修复章节时发生错误: {Path.GetFileName(chapterFile)}");
                        result.FailedChapters.Add(Path.GetFileName(chapterFile));
                    }
                }

                result.IsSuccess = result.FailedChapters.Count == 0;
                result.Message = $"修复完成。成功: {result.RepairedChapters.Count}, 失败: {result.FailedChapters.Count}";

                _logger.LogInformation(result.Message);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "修复项目章节时发生错误");
                result.IsSuccess = false;
                result.Message = $"修复过程中发生错误: {ex.Message}";
            }

            return result;
        }

        /// <summary>
        /// 修复单个章节
        /// </summary>
        private async Task<bool> RepairSingleChapterAsync(
            string chapterFilePath, 
            string projectPath, 
            CancellationToken cancellationToken)
        {
            try
            {
                // 读取原始内容
                var originalContent = await File.ReadAllTextAsync(chapterFilePath);
                
                // 解析章节信息
                var chapterInfo = ParseChapterInfo(chapterFilePath);
                if (chapterInfo == null)
                {
                    _logger.LogWarning($"无法解析章节信息: {chapterFilePath}");
                    return false;
                }

                // 查找对应的章节细纲
                var outlineContent = await FindChapterOutlineAsync(projectPath, chapterInfo.ChapterNumber);
                if (string.IsNullOrEmpty(outlineContent))
                {
                    _logger.LogWarning($"找不到第{chapterInfo.ChapterNumber}章的细纲");
                    return false;
                }

                // 构建上下文
                var context = await BuildRepairContextAsync(projectPath, chapterInfo.ChapterNumber);

                // 重新生成章节内容
                var newContent = await RegenerateChapterContentAsync(
                    outlineContent, 
                    context, 
                    chapterInfo.ChapterNumber,
                    cancellationToken);

                if (string.IsNullOrEmpty(newContent))
                {
                    _logger.LogWarning($"重新生成第{chapterInfo.ChapterNumber}章内容失败");
                    return false;
                }

                // 验证新内容质量
                var qualityResult = _contentQualityService.CheckChapterContent(newContent, 6500);
                if (!qualityResult.IsValid)
                {
                    _logger.LogWarning($"重新生成的第{chapterInfo.ChapterNumber}章内容质量仍不合格");
                    // 使用清理后的内容
                    newContent = qualityResult.CleanedContent;
                }

                // 备份原文件
                var backupPath = chapterFilePath + ".backup." + DateTime.Now.ToString("yyyyMMdd_HHmmss");
                await File.WriteAllTextAsync(backupPath, originalContent);

                // 保存新内容
                await File.WriteAllTextAsync(chapterFilePath, newContent);

                _logger.LogInformation($"成功修复章节: {Path.GetFileName(chapterFilePath)}，备份保存至: {Path.GetFileName(backupPath)}");
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"修复单个章节失败: {chapterFilePath}");
                return false;
            }
        }

        /// <summary>
        /// 检查是否有严重问题
        /// </summary>
        private bool HasCriticalIssues(string content)
        {
            if (string.IsNullOrWhiteSpace(content))
                return true;

            // 检查是否包含错误信息
            var errorIndicators = new[]
            {
                "由于您提供的",
                "缺少具体的情节描述",
                "请您补充完整章节",
                "生成失败",
                "此处省略部分重复内容",
                "（此处为完整的第",
                "章小说章节内容"
            };

            if (errorIndicators.Any(indicator => content.Contains(indicator)))
                return true;

            // 检查内容是否过短
            if (content.Length < 500)
                return true;

            // 检查是否主要是大纲格式
            var outlineMarkers = Regex.Matches(content, @"###|第.*?章|章节.*?：|\*\*.*?\*\*").Count;
            var totalLines = content.Split('\n', StringSplitOptions.RemoveEmptyEntries).Length;
            
            if (totalLines > 0 && (double)outlineMarkers / totalLines > 0.3)
                return true;

            return false;
        }

        /// <summary>
        /// 解析章节信息
        /// </summary>
        private ChapterInfo? ParseChapterInfo(string filePath)
        {
            var fileName = Path.GetFileNameWithoutExtension(filePath);
            
            // 匹配文件名格式：书名_第XX卷_卷名_第XXX章_章节名
            var match = Regex.Match(fileName, @"第(\d+)章");
            if (match.Success && int.TryParse(match.Groups[1].Value, out int chapterNumber))
            {
                return new ChapterInfo
                {
                    ChapterNumber = chapterNumber,
                    FilePath = filePath
                };
            }

            return null;
        }

        /// <summary>
        /// 查找章节细纲
        /// </summary>
        private async Task<string> FindChapterOutlineAsync(string projectPath, int chapterNumber)
        {
            var outlinePath = Path.Combine(projectPath, "大纲", "章节细纲");
            if (!Directory.Exists(outlinePath))
                return string.Empty;

            var outlineFiles = Directory.GetFiles(outlinePath, "*.txt", SearchOption.TopDirectoryOnly);
            
            foreach (var file in outlineFiles)
            {
                var fileName = Path.GetFileNameWithoutExtension(file);
                if (fileName.Contains($"第{chapterNumber:D3}章") || fileName.Contains($"第{chapterNumber}章"))
                {
                    return await File.ReadAllTextAsync(file);
                }
            }

            return string.Empty;
        }

        /// <summary>
        /// 构建修复上下文
        /// </summary>
        private async Task<string> BuildRepairContextAsync(string projectPath, int chapterNumber)
        {
            var context = new List<string>();

            // 添加总体大纲
            var overallOutlinePath = Path.Combine(projectPath, "大纲", "*总体大纲*.txt");
            var overallOutlineFiles = Directory.GetFiles(Path.GetDirectoryName(overallOutlinePath)!, Path.GetFileName(overallOutlinePath));
            if (overallOutlineFiles.Length > 0)
            {
                var outline = await File.ReadAllTextAsync(overallOutlineFiles[0]);
                if (outline.Length > 800)
                    outline = outline.Substring(0, 800) + "...";
                context.Add($"全书大纲：{outline}");
            }

            // 添加前一章内容摘要
            if (chapterNumber > 1)
            {
                var previousChapterPath = await FindChapterFileAsync(projectPath, chapterNumber - 1);
                if (!string.IsNullOrEmpty(previousChapterPath))
                {
                    var previousContent = await File.ReadAllTextAsync(previousChapterPath);
                    var ending = GetChapterEnding(previousContent);
                    if (!string.IsNullOrEmpty(ending))
                    {
                        context.Add($"前一章结尾：{ending}");
                    }
                }
            }

            return string.Join("\n\n", context);
        }

        /// <summary>
        /// 查找章节文件
        /// </summary>
        private async Task<string> FindChapterFileAsync(string projectPath, int chapterNumber)
        {
            var chapterPath = Path.Combine(projectPath, "章节");
            if (!Directory.Exists(chapterPath))
                return string.Empty;

            var chapterFiles = Directory.GetFiles(chapterPath, "*.txt", SearchOption.TopDirectoryOnly);
            
            foreach (var file in chapterFiles)
            {
                var fileName = Path.GetFileNameWithoutExtension(file);
                if (fileName.Contains($"第{chapterNumber:D3}章") || fileName.Contains($"第{chapterNumber}章"))
                {
                    return file;
                }
            }

            return string.Empty;
        }

        /// <summary>
        /// 获取章节结尾
        /// </summary>
        private string GetChapterEnding(string content)
        {
            if (string.IsNullOrEmpty(content))
                return string.Empty;

            var lines = content.Split('\n', StringSplitOptions.RemoveEmptyEntries);
            if (lines.Length == 0)
                return string.Empty;

            // 取最后几行作为结尾
            var endingLines = lines.TakeLast(Math.Min(3, lines.Length));
            var ending = string.Join("\n", endingLines);

            // 限制长度
            if (ending.Length > 200)
                ending = ending.Substring(ending.Length - 200);

            return ending;
        }

        /// <summary>
        /// 重新生成章节内容
        /// </summary>
        private async Task<string> RegenerateChapterContentAsync(
            string outline, 
            string context, 
            int chapterNumber,
            CancellationToken cancellationToken)
        {
            var prompt = $@"你是一位专业的小说作家，请根据以下章节细纲重新创作第{chapterNumber}章的完整内容。

=== 章节细纲 ===
{outline}

=== 上下文信息 ===
{context}

=== 创作要求 ===
1. 必须写成标准的小说正文格式，约6500字
2. 包含丰富的场景描写、人物对话、心理描写、动作描写
3. 严格按照细纲发展情节，但要用生动的小说语言表现
4. 不要写成大纲、摘要或分析形式
5. 不要包含任何标题、章节号或结构性标记
6. 确保情节完整、逻辑连贯
7. 人物性格鲜明，对话自然
8. 营造适当的氛围和节奏

请直接创作小说正文：";

            return await _aiService.GenerateTextAsync(prompt, 8000, 0.8f);
        }

        /// <summary>
        /// 章节信息
        /// </summary>
        private class ChapterInfo
        {
            public int ChapterNumber { get; set; }
            public string FilePath { get; set; } = string.Empty;
        }
    }
}
